package com.pinyoumei.app.activity.ShoppingCenter.taobao;

import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.pinyoumei.app.R;
import com.pinyoumei.app.adapter.TaoBaoOrderAdapter;
import com.pinyoumei.app.bean.TaoBaoOrderBean;
import com.pinyoumei.app.fragment.BaseLazyLoadFragment;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.DateTimeUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.view.LoadingDailog;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2020-12-14.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2020-12-14        Administrator             新增Person类
 * 2020-12-14        Administrator             增加sex属性
 * 淘宝专区订单
 */
public class ToaBaoBillFragment extends BaseLazyLoadFragment implements View.OnClickListener {
    private TextView textTypeName;
    private TimePickerView datepickview;//日期选择器
    private TabLayout tabMachines;
    private int page = 1;

    private List<TaoBaoOrderBean.ResultBean.OrderListBean>  balance_detail_list = new ArrayList<>();
    private String time = "";
    private int deal_kind = -1;
    private boolean First_Visible = true;
    private String[] mTitle = {"全部", "已付款" ,"已收货" ,"已失效" ,"已结算"};


    private Gson gson;
    private LoadingDailog loadingDailog;
    private RequestOptions placeholder;
    private TaoBaoOrderAdapter taoBaoOrderAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_taobao_bill;
    }

    @Override
    public void initView(View rootView) {
        gson = new Gson();
        LoadingDailog.Builder builder = new LoadingDailog.Builder(getActivity())
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();

        placeholder = new RequestOptions().placeholder(R.mipmap.ic_error_loading);
        RelativeLayout relativeFinish = rootView.findViewById(R.id.relative_finish);
        relativeFinish.setOnClickListener(this);
        LinearLayout linearType = rootView.findViewById(R.id.linear_type);
        linearType.setOnClickListener(this);
        initPickerTime();
        textTypeName = rootView.findViewById(R.id.text_type_name);

        time = DateTimeUtils.stampToDate2(String.valueOf(System.currentTimeMillis()));//获取系统时间戳
        textTypeName.setText(time);//设置当月时间

        tabMachines = rootView.findViewById(R.id.tab_machines);
        for (int i = 0; i < mTitle.length; i++) {
            tabMachines.addTab(tabMachines.newTab().setTag(i).setText(mTitle[i]));
        }
        tabMachines.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                    balance_detail_list.clear();
                    deal_kind = (int) tab.getTag();
                    page = 1;
                    InitData(deal_kind,time);


            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


        SmartRefreshLayout refreshLayout = rootView.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                balance_detail_list.clear();
                InitData(deal_kind,time);
                refreshLayout.finishRefresh();
            }
        });


        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page ++;
                LoadMoreData(deal_kind,time);
                refreshLayout.finishLoadMore();
            }
        });
        RecyclerView recyclerview = rootView.findViewById(R.id.recyclerview);
        recyclerview.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
        taoBaoOrderAdapter = new TaoBaoOrderAdapter(R.layout.item_shop_order,null);
        recyclerview.setAdapter(taoBaoOrderAdapter);
        View  notDataView = getLayoutInflater().inflate(R.layout.item_empty_view, (ViewGroup) recyclerview.getParent(), false);
        taoBaoOrderAdapter.setEmptyView(notDataView);


    }




    private void initPickerTime() {
        Calendar selectedDate = Calendar.getInstance();

        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        //正确设置方式 原因：注意事项有说明
        startDate.set(2000, 0, 1);
        //endDate.set(2100,11,31);
        //起始身份证日期选择
        datepickview  = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//账单日时间选择的回调
                //2019.03.15
                balance_detail_list.clear();
                time =  DateTimeUtils.stampToDate2(date.getTime()+"");
                textTypeName.setText(time);
                InitData(deal_kind,time);
            }
        }).setLabel("年", "月", "", "", "", "")//默认设置为年月日时分秒
                .setType(new boolean[]{true, true, false, false, false, false})// 默认全部显示
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setContentTextSize(18)//滚轮文字大小
                .setTitleSize(17)//标题文字大小
                .isDialog(false)//是否显示为对话框样式
                .setTitleText("")//设置标题
                .setTitleSize(17)//设置标题字体大小
                .setTitleColor(Color.parseColor("#ff000000"))//设置标题字体颜色
                .setCancelColor(Color.parseColor("#ff000000"))//设置取消字体颜色
                .setSubmitColor(Color.parseColor("#448FF6"))//设置确定字体颜色
                .setDividerColor(Color.parseColor("#E6E6E6"))//设置分割线的颜色
                .setTextColorCenter(Color.parseColor("#ff323232")) //设置选中项文字颜色
                .build();
    }

    @Override
    public void onFragmentVisible() {
        super.onFragmentVisible();
        if ( First_Visible ){
            InitData(deal_kind,time);
        }

    }

    private void InitData(int order_status, String order_time) {

//        订单来源 1：淘宝 2：京东 3：拼多多 4：唯品会5：外卖专区
        Map<String, Object> map = new HashMap<>();
        map.put("user_id",  SPUtils.getAppUserId(getActivity()));
        map.put("order_status", order_status);
        map.put("order_time",order_time);
        map.put("order_source",1);
        map.put("page", page);
        map.put("limit", 10);


        OkGo.<String>post(Constants.BILL_ORDER_LIST)
                .params("user_id",  SPUtils.getAppUserId(getActivity()))
                .params("order_status", order_status)
                .params("order_time",order_time)
                .params("order_source",1)
                .params("page", page)
                .params("limit", 10)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {




                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        First_Visible = false;
                        TaoBaoOrderBean toBaoBean = gson.fromJson(response.body(), TaoBaoOrderBean.class);
                        if (toBaoBean.getCode() >= 0) {
                            balance_detail_list.addAll(toBaoBean.getResult().getOrder_list()) ;
                            taoBaoOrderAdapter.setNewData(balance_detail_list);
                        } else {
                            ToastUtils.showShort(toBaoBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });



    }


    private void LoadMoreData(int order_status, String order_time) {

//        订单来源 1：淘宝 2：京东 3：拼多多 4：唯品会5：外卖专区
        Map<String, Object> map = new HashMap<>();
        map.put("user_id",  SPUtils.getAppUserId(getActivity()));
        map.put("order_status", order_status);
        map.put("order_time",order_time);
        map.put("order_source",1);
        map.put("page", page);
        map.put("limit", 10);


        OkGo.<String>post(Constants.BILL_ORDER_LIST)
                .params("user_id",  SPUtils.getAppUserId(getActivity()))
                .params("order_status", order_status)
                .params("order_time",order_time)
                .params("order_source",1)
                .params("page", page)
                .params("limit", 10)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {




                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        First_Visible = false;
                        TaoBaoOrderBean toBaoBean = gson.fromJson(response.body(), TaoBaoOrderBean.class);
                        if (toBaoBean.getCode() >= 0) {
//                            balance_detail_list.addAll(toBaoBean.getResult().getOrder_list()) ;
                            taoBaoOrderAdapter.addData(toBaoBean.getResult().getOrder_list());
                        } else {
                            ToastUtils.showShort(toBaoBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        	case R.id.relative_finish :
        	    getActivity().finish();
        		break;
            case R.id.linear_type:
                datepickview.show();
                break;
        	default:
        		break;
        }
    }
}
